package com.ztgf.shopping.service.audit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.models.dto.CommodityCategoryDTO;
import com.ztgf.commodity.models.service.ICommodityCategoryService;
import com.ztgf.common.constant.CommonParameter;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.db.utils.RedisUtil;
import com.ztgf.file.models.bo.FileInfoSaveBO;
import com.ztgf.file.models.dto.FileInfoDTO;
import com.ztgf.file.models.service.IFileInfoService;
import com.ztgf.file.models.service.IFileService;
import com.ztgf.file.models.vo.FileInfoVO;
import com.ztgf.logistics.models.bo.deppon.LogisticsAuditBO;
import com.ztgf.logistics.models.dto.deppon.LogisticsUserDTO;
import com.ztgf.logistics.models.service.deppon.ILogisticsUserService;
import com.ztgf.message.model.bo.MessageAnnouncementSaveBO;
import com.ztgf.message.model.constant.MessageTopicType;
import com.ztgf.message.model.dto.ResponseDTO;
import com.ztgf.message.model.enums.MessageEnum;
import com.ztgf.message.model.service.IKafkaProducerService;
import com.ztgf.order.models.bo.purchase.PurchaseInfoImportSaveBO;
import com.ztgf.order.models.bo.purchase.PurchaseInfoSaveBO;
import com.ztgf.order.models.service.purchase.IPurchaseInfoService;
import com.ztgf.shopping.common.config.YmlConfig;
import com.ztgf.shopping.mapper.audit.AuditMapper;
import com.ztgf.shopping.mapper.shop.ShopInfoMapper;
import com.ztgf.shopping.models.bo.audit.AuditBO;
import com.ztgf.shopping.models.bo.audit.AuditImportPurchaseSaveBO;
import com.ztgf.shopping.models.bo.audit.AuditSaveBO;
import com.ztgf.shopping.models.bo.shop.ShopInfoAuditBO;
import com.ztgf.shopping.models.dto.audit.AuditDTO;
import com.ztgf.shopping.models.dto.audit.AuditDeBangDTO;
import com.ztgf.shopping.models.dto.audit.AuditLogDTO;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.enums.ShoppingCodeEnum;
import com.ztgf.shopping.models.service.audit.IAuditDebangService;
import com.ztgf.shopping.models.service.audit.IAuditLogService;
import com.ztgf.shopping.models.service.audit.IAuditService;
import com.ztgf.shopping.models.vo.audit.AuditLogVO;
import com.ztgf.shopping.models.vo.audit.AuditTreeVO;
import com.ztgf.shopping.models.vo.audit.AuditVO;
import com.ztgf.shopping.models.vo.audit.RegisterShopVO;
import com.ztgf.shopping.models.vo.shop.CommodityCategoryTreeVO;
import com.ztgf.sys.models.dto.SysUserDTO;
import com.ztgf.user.models.dto.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@DubboService
public class AuditServiceImpl extends ServiceImpl<AuditMapper, AuditDTO> implements IAuditService {
    @Resource
    private YmlConfig ymlConfig;
    @Resource
    private IAuditLogService auditLogService;
    @DubboReference
    private ICommodityCategoryService iCommodityCategoryService;
    @DubboReference
    private IPurchaseInfoService purchaseInfoService;
    @DubboReference
    private IFileService fileService;
    @DubboReference
    private IKafkaProducerService kafkaProducerService;
    @DubboReference
    private IFileInfoService fileInfoService;
    @DubboReference
    private ILogisticsUserService logisticsUserService;

    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private IAuditDebangService auditDebangService;
    @Autowired
    private ShopInfoMapper shopInfoMapper;

    @Override
    public Result save(AuditSaveBO bo,FileInfoSaveBO saveBO) {
        if(StrUtils.isEmpty(bo.getParams())){
            return new Result(CodeEnum.FAIL_100002);
        }

        if(bo.getId() == null){//添加
            if(bo.getShopId() == null || bo.getType() == null){
                return new Result(CodeEnum.FAIL_100002);
            }
            checkParams(bo.getType(), bo.getParams());

            ShopInfoDTO shopDTO = shopInfoMapper.selectById(bo.getShopId());
            if(shopDTO == null){
                return new Result(CodeEnum.FAIL_100002);
            }

            Long userId = null;
            String userName = "";
            Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
            if(object == null){
                return new Result(CodeEnum.FAIL_100002);
            }
            if(object instanceof UserInfoDTO){
                userId = ((UserInfoDTO) object).getId ();
                userName = ((UserInfoDTO) object).getName ();
            } if(object instanceof SysUserDTO){
                userId = ((SysUserDTO) object).getId ();
                userName = ((SysUserDTO) object).getName ();
            }
            AuditDTO auditDTO = new AuditDTO();
            auditDTO.setCreateUserId(userId);
            auditDTO.setCreateUserName(userName);
            auditDTO.setUserId(userId);
            auditDTO.setParams(bo.getParams());
            auditDTO.setShopId(shopDTO.getId());
            auditDTO.setName(shopDTO.getName());
            auditDTO.setShopName(shopDTO.getShopName());
            auditDTO.setType(bo.getType());
            auditDTO.setStatus(0);
            addDTO(auditDTO,saveBO);

        } else {//修改
            if(bo.getStatus() == null){
                return new Result(CodeEnum.FAIL_100002);
            }

            if(bo.getStatus() == 2 || bo.getStatus() == 3){
                if(StrUtils.isEmpty(bo.getContent())){
                    return new Result(CodeEnum.FAIL_100002);
                }
            }

            AuditDTO auditDTO = this.selectById(bo.getId());
            if(auditDTO == null){
                return new Result(CodeEnum.FAIL_100002);
            }
            checkParams(auditDTO.getType(), bo.getParams());
            Long userId = null;
            String userName = "";

            Object object = redisUtil.getSession (CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
            if(object == null){
                return new Result(CodeEnum.FAIL_100002);
            }
            if(object instanceof UserInfoDTO){
                userId = ((UserInfoDTO) object).getId ();
                userName = ((UserInfoDTO) object).getName ();
            } if(object instanceof SysUserDTO){
                userId = ((SysUserDTO) object).getId ();
                userName = ((SysUserDTO) object).getName ();
            }
            auditDTO.setUpdateUserId(userId);
            auditDTO.setUpdateUserName(userName);
            auditDTO.setUpdateTime(null);
            auditDTO.setParams(bo.getParams());
            auditDTO.setContent(bo.getContent());
            auditDTO.setStatus(bo.getStatus());
            editDTO(auditDTO);
        }
        return new Result();
    }

    @Override
    public Result save(AuditSaveBO bo) {
        if(bo.getId() == null){//添加
            if(bo.getShopId() == null || bo.getType() == null){
                return new Result(CodeEnum.FAIL_100002);
            }
            checkParams(bo.getType(), bo.getParams());

            if(!(bo.getType() == 2 || bo.getType() == 3 || bo.getType() == 4 || bo.getType() == 6)){//只有一条审核记录
                //审核状态 0审核中，1审核通过，2审核打回，3审核不通过,4重新提交
                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("shop_id", bo.getShopId());
                wrapper.eq("type", bo.getType());
                wrapper.in("status", "0,2,4");
                wrapper.last("limit 1");
                AuditDTO auditDTO = this.selectOne(wrapper);
                if(auditDTO != null){
                    return new Result<>(CodeEnum.FAIL_100060);
                }
            }

            ShopInfoDTO shopDTO = shopInfoMapper.selectById(bo.getShopId());
            if(shopDTO == null){
                return new Result(CodeEnum.FAIL_100002);
            }

            Long userId = null;
            String userName = "";
            Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
            if(object == null){
                return new Result(CodeEnum.FAIL_100002);
            }
            if(object instanceof UserInfoDTO){
                userId = ((UserInfoDTO) object).getId ();
                userName = ((UserInfoDTO) object).getName ();
            } if(object instanceof SysUserDTO){
                userId = ((SysUserDTO) object).getId ();
                userName = ((SysUserDTO) object).getName ();
            }
            AuditDTO auditDTO = new AuditDTO();
            auditDTO.setCreateUserId(userId);
            auditDTO.setCreateUserName(userName);
            auditDTO.setUserId(userId);
            auditDTO.setParams(bo.getParams());
            auditDTO.setShopId(shopDTO.getId());
            auditDTO.setName(shopDTO.getName());
            auditDTO.setShopName(shopDTO.getShopName());
            auditDTO.setType(bo.getType());
            auditDTO.setStatus(0);
            log.info("===============开始录入关联数据"+bo);
            //德邦关联表
            AuditDeBangDTO auditDeBangDTO = new AuditDeBangDTO();
            auditDeBangDTO.setFinanceName(bo.getFinanceName());
            auditDeBangDTO.setFinancePhone(bo.getFinancePhone());
            auditDeBangDTO.setFinanceWx(bo.getFinanceWx());
            auditDeBangDTO.setFinanceQq(bo.getFinanceQq());
            auditDeBangDTO.setSendName(bo.getSendName());
            auditDeBangDTO.setSendPhone(bo.getSendPhone());
            auditDeBangDTO.setSendWx(bo.getSendWx());
            auditDeBangDTO.setSendQq(bo.getSendQq());
            log.info("===============auditDeBangDTO"+auditDeBangDTO);
            addDTO(auditDTO,auditDeBangDTO);

        } else {//修改
            if(bo.getStatus() == null){
                return new Result(CodeEnum.FAIL_100002);
            }

            if(bo.getStatus() == 2 || bo.getStatus() == 3){
                if(StrUtils.isEmpty(bo.getContent())){
                    return new Result(CodeEnum.FAIL_100002);
                }
            }

            AuditDTO auditDTO = this.selectById(bo.getId());
            if(auditDTO == null){
                return new Result(CodeEnum.FAIL_100002);
            }
            checkParams(auditDTO.getType(), bo.getParams());
            Long userId = null;
            String userName = "";
            Object object = redisUtil.getSession (CommonParameter.getHeadParamsBO ().getSessionId (), CommonParameter.getHeadParamsBO ().getSource ().toString ());
            if(object == null){
                return new Result(CodeEnum.FAIL_100002);
            }
            if(object instanceof UserInfoDTO){
                userId = ((UserInfoDTO) object).getId ();
                userName = ((UserInfoDTO) object).getName ();
            } if(object instanceof SysUserDTO){
                userId = ((SysUserDTO) object).getId ();
                userName = ((SysUserDTO) object).getName ();
            }

            auditDTO.setUpdateUserId(userId);
            auditDTO.setUpdateUserName(userName);
            auditDTO.setUpdateTime(null);
            auditDTO.setParams(bo.getParams());
            auditDTO.setContent(bo.getContent());
            auditDTO.setStatus(bo.getStatus());
            editDTO(auditDTO);
        }
        return new Result();
    }

    @Transactional(rollbackFor=Exception.class)
    public void addDTO(AuditDTO auditDTO,AuditDeBangDTO auditDeBangDTO){
        boolean success = this.insertOrUpdate(auditDTO);

        auditDeBangDTO.setId(auditDTO.getId());
        log.info("===================结果111"+auditDeBangDTO);
        boolean insert = auditDebangService.insert(auditDeBangDTO);
        log.info("===================结果"+insert);
        AuditLogDTO logDTO = new AuditLogDTO();
        logDTO.setId(ymlConfig.getPkId());
        logDTO.setAuditId(auditDTO.getId());
        logDTO.setCreateUserId(auditDTO.getCreateUserId());
        logDTO.setCreateUserName(auditDTO.getCreateUserName());
        logDTO.setParams(auditDTO.getParams());
        logDTO.setUserId(auditDTO.getUserId());
        logDTO.setName(auditDTO.getName());
        logDTO.setShopName(auditDTO.getShopName());
        logDTO.setType(auditDTO.getType());
        logDTO.setStatus(auditDTO.getStatus());
        logDTO.setAuditId(auditDTO.getId());
        logDTO.setShopId(auditDTO.getShopId());
        logDTO.setContent(auditDTO.getContent());
        boolean logSuccess = auditLogService.insert(logDTO);
        if(!(success && logSuccess)){
            throw new ServiceException(CodeEnum.FAIL_100007);
        }

        if(7 == auditDTO.getType()){
            LogisticsUserDTO userDTO = new LogisticsUserDTO();
            userDTO.setId(auditDTO.getShopId());
            userDTO.setAuditId(auditDTO.getId());
            boolean flag = logisticsUserService.updateById(userDTO);
            if(!flag){
                throw new ServiceException(CodeEnum.FAIL_100007);
            }
        }

    }
    //发送消息 只有站内信
    private void urgeSignContact(String conunt, Long sellShopId, Integer shopType, Integer textType) {
        MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();

        if (shopType.equals(ShoppingCodeEnum.MERCHANT_BUYER.getCode())) {
            //买家
            messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_1.getCode());
        } else {
            messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_2.getCode());
        }

        ResponseDTO responseDTO = new ResponseDTO();
        messageAnnouncementSaveBO.setContent(conunt);
        messageAnnouncementSaveBO.setShopId(sellShopId);
        messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
        messageAnnouncementSaveBO.setTitle("物流月结申请拒绝通知");
        messageAnnouncementSaveBO.setJumpType(MessageEnum.MESSAGE_SHOW.getCode() + "");
        messageAnnouncementSaveBO.setTextType(textType);
        messageAnnouncementSaveBO.setKey(sellShopId + "");
        responseDTO.setData(messageAnnouncementSaveBO);
        responseDTO.setMessageId(sellShopId + "");
        kafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
    }
    @Transactional(rollbackFor=Exception.class)
    public void addDTO(AuditDTO auditDTO,FileInfoSaveBO fileSaveBO){
        boolean success = this.insertOrUpdate(auditDTO);
        AuditLogDTO logDTO = new AuditLogDTO();
        logDTO.setId(ymlConfig.getPkId());
        logDTO.setAuditId(auditDTO.getId());
        logDTO.setCreateUserId(auditDTO.getCreateUserId());
        logDTO.setCreateUserName(auditDTO.getCreateUserName());
        logDTO.setParams(auditDTO.getParams());
        logDTO.setUserId(auditDTO.getUserId());
        logDTO.setName(auditDTO.getName());
        logDTO.setShopName(auditDTO.getShopName());
        logDTO.setType(auditDTO.getType());
        logDTO.setStatus(auditDTO.getStatus());
        logDTO.setAuditId(auditDTO.getId());
        logDTO.setShopId(auditDTO.getShopId());
        logDTO.setContent(auditDTO.getContent());
        boolean logSuccess = auditLogService.insert(logDTO);
        if(!(success && logSuccess)){
            throw new ServiceException(CodeEnum.FAIL_100007);
        }
        try {
            fileSaveBO.setShopId(auditDTO.getId());//保存审核表id
            FileInfoVO vo = fileService.uploadFile(fileSaveBO);
        }catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Transactional(rollbackFor=Exception.class)
    public void editDTO(AuditDTO auditDTO){
        Wrapper wrapper = new EntityWrapper();
        int revision = auditDTO.getRevision();
        wrapper.eq("id", auditDTO.getId());
        wrapper.eq("revision", revision);
        auditDTO.setRevision(revision + 1);
        boolean success = this.update(auditDTO, wrapper);
        AuditLogDTO logDTO = new AuditLogDTO();
        logDTO.setId(ymlConfig.getPkId());
        logDTO.setAuditId(auditDTO.getId());
        logDTO.setCreateUserId(auditDTO.getUpdateUserId());
        logDTO.setCreateUserName(auditDTO.getUpdateUserName());
        logDTO.setParams(auditDTO.getParams());
        logDTO.setUserId(auditDTO.getUserId());
        logDTO.setName(auditDTO.getName());
        logDTO.setShopName(auditDTO.getShopName());
        logDTO.setType(auditDTO.getType());
        logDTO.setStatus(auditDTO.getStatus());
        logDTO.setAuditId(auditDTO.getId());
        logDTO.setShopId(auditDTO.getShopId());
        logDTO.setContent(auditDTO.getContent());
        boolean logSuccess = auditLogService.insert(logDTO);
        if(!(success && logSuccess)){
            throw new ServiceException(CodeEnum.FAIL_100008);
        }

        if(6 == auditDTO.getType() && 1 == auditDTO.getStatus()){
            PurchaseInfoSaveBO saveBO = JSONObject.parseObject(auditDTO.getParams(), PurchaseInfoSaveBO.class);
            saveBO.setCreateUserId(auditDTO.getCreateUserId());
            saveBO.setCreateUserName(auditDTO.getCreateUserName());
            saveBO.setPublishType(0);
            purchaseInfoService.add(saveBO,auditDTO);
        } else if(7 == auditDTO.getType() && 1 == auditDTO.getStatus()){
            LogisticsAuditBO auditBO = JSONObject.parseObject(auditDTO.getParams(), LogisticsAuditBO.class);
            if(auditBO.getLogisticsMoneyQuota().compareTo(BigDecimal.ZERO) < 0 || auditBO.getMguaranteeMoneyQuota().compareTo(BigDecimal.ZERO) < 0){
                throw new ServiceException(CodeEnum.FAIL_100073);
            }

            auditBO.setAuditId(auditDTO.getId());
            auditBO.setShopId(auditDTO.getShopId());
            logisticsUserService.saveAudit(auditBO);
        }
        //物流审核不通过发送站内信
        if (7 == auditDTO.getType() && 3 == auditDTO.getStatus()){
            log.info("物流审核不通过发送站内信=================");
            String content="因为“"+auditDTO.getContent()+"”原因，您的物流月结申请被拒绝，请联系客服或重新递交!";
                urgeSignContact(content,auditDTO.getShopId(),0,1);
        }
    }

    private void checkParams(int type, String params){
        if(StrUtils.isNotEmpty(params)){
            if(type == 6){
                PurchaseInfoSaveBO saveBO = JSONObject.parseObject(params, PurchaseInfoSaveBO.class);
                if(saveBO == null){
                    throw new ServiceException(CodeEnum.FAIL_100002);
                }

                if(saveBO.getCommoditySaveBOList() == null || saveBO.getCommoditySaveBOList().size() == 0){
                    throw new ServiceException(CodeEnum.FAIL_100002);
                }
            }
        }
    }


    @Override
    public boolean add(AuditDTO auditDTO) {
        auditDTO.setId(ymlConfig.getPkId());
        this.insert(auditDTO);
        //添加日志表
        return auditLogService.add(auditDTO.getId(), auditDTO.getStatus() );

    }

    @Override
    public boolean update(AuditDTO auditDTO) {
        //添加日志表
        this.updateById(auditDTO);
        return auditLogService.updateOpt(auditDTO.getId());
    }

    @Override
    public Integer getNum(Integer type) {
        return  baseMapper.getNum(type);
    }

    @Override
    public Integer getNum1(Integer type, Integer type1) {
        return  baseMapper.getNum1(type,type1);
    }

    @Override
    public Integer getNumByTab(Integer type, Long shopId) {
        Wrapper<AuditDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        wrapper.eq("status", ShoppingCodeEnum.AUDIT_CREATE.getCode());

        if (type.equals(3)){
            wrapper.eq("type", ShoppingCodeEnum.AUDIT_TYPE_INSERTCATEGORY.getCode());
            return baseMapper.selectCount(wrapper);
        }

        if (type.equals(1)){
            wrapper.eq("type", ShoppingCodeEnum.AUDIT_TYPE_CHANGE.getCode());
            List<AuditDTO> auditDTOList = baseMapper.selectList(wrapper);
            int num = 0;
            for (AuditDTO auditDTO : auditDTOList){
                RegisterShopVO registerShopVO = JSONObject.parseObject(auditDTO.getParams(), RegisterShopVO.class);
                List<RegisterShopVO.QualificationInfoVO> qualificationInfoVOList = registerShopVO.getQualificationInfoVOList();
                for (RegisterShopVO.QualificationInfoVO vo : qualificationInfoVOList){
                    if (Integer.parseInt(vo.getQtype().getValue()) <= ShoppingCodeEnum.QUALIFICATION_ACCOUNT.getCode()){
                        num ++;
                        break;
                    }
                }

            }
            return num;
        }

        if (type.equals(2)){
            wrapper.eq("type", ShoppingCodeEnum.AUDIT_TYPE_CHANGE.getCode());
            List<AuditDTO> auditDTOList = baseMapper.selectList(wrapper);
            int bnum = 0;
            for (AuditDTO auditDTO : auditDTOList){
                RegisterShopVO registerShopVO = JSONObject.parseObject(auditDTO.getParams(), RegisterShopVO.class);
                List<RegisterShopVO.QualificationInfoVO> qualificationInfoVOList = registerShopVO.getQualificationInfoVOList();
                for (RegisterShopVO.QualificationInfoVO vo : qualificationInfoVOList){
                    if (Integer.parseInt(vo.getQtype().getValue()) > ShoppingCodeEnum.QUALIFICATION_ACCOUNT.getCode()){
                        bnum ++;
                        break;
                    }
                }
            }

            Wrapper<AuditDTO> qwrapper = new EntityWrapper<>();
            qwrapper.eq("shop_id", shopId);
            qwrapper.eq("status", ShoppingCodeEnum.AUDIT_CREATE.getCode());
            qwrapper.eq("type", ShoppingCodeEnum.AUDIT_TYPE_INSERTBRAND.getCode());
            int qnum = baseMapper.selectCount(qwrapper);
            return  bnum + qnum;
        }
        return 0;
    }

    @Override
    public Page<AuditVO> queryPageList(ShopInfoAuditBO bo) {
        Page<AuditVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<AuditVO> auditVOList = baseMapper.queryPageList(page, bo);
        for (AuditVO vo : auditVOList){
            if (vo.getType().equals(ShoppingCodeEnum.AUDIT_TYPE_CHANGE.getCode())){
                String s_type = "\"qtype\":{\"value\":\"";
                Integer qtype_index = vo.getParams().indexOf(s_type);
                if (qtype_index > -1) {
                    Integer qtype = Integer.parseInt(vo.getParams().substring(qtype_index + s_type.length(), qtype_index + s_type.length() + 1));
                    vo.setQtype(qtype);
                }
            }
        }
        page.setRecords(auditVOList);
        return page;
    }

    @Override
    public Result<List<AuditTreeVO>> queryTreeList(Long id) {
        ArrayList<AuditTreeVO> auditTreeVOS = new ArrayList<>();
        AuditDTO auditDTO = this.selectById(id);
        if (auditDTO == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        RegisterShopVO registerShopVO = JSONObject.parseObject(auditDTO.getParams(), RegisterShopVO.class);

        Integer auditType = Integer.parseInt(registerShopVO.getAuditType().getValue());
        if (auditType.equals(ShoppingCodeEnum.AUDIT_TYPE_INSERTBRAND.getCode()) || auditType.equals(ShoppingCodeEnum.AUDIT_TYPE_INSERTCATEGORY.getCode())){
            for (RegisterShopVO.BrandAuditVO brandAuditVO : registerShopVO.getBrandAuditVOList()){
                ArrayList<Long> ids = new ArrayList<>();
                String brandName = brandAuditVO.getName().getValue();
                for (RegisterShopVO.BrandCategoryVO brandCategoryVO : brandAuditVO.getBrandCategoryVOList()){
                    ids.add(Long.parseLong(brandCategoryVO.getCategoryId().getValue()));
                }
                List<CommodityCategoryTreeVO> commodityCategoryTreeVOS = getCTree(ids);

                AuditTreeVO vo = new AuditTreeVO();
                vo.setBrandName(brandName);
                vo.setCommodityCategoryTreeVOList(commodityCategoryTreeVOS);
                auditTreeVOS.add(vo);
            }
        }
        return new Result<>(auditTreeVOS);
    }

    @Override
    public Page<AuditVO> queryPageListNew(AuditBO bo) {
        Page<AuditVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<AuditVO> auditVOList = baseMapper.queryPageListNew(page, bo);
        for(AuditVO auditVO : auditVOList){
            Wrapper<FileInfoDTO> fileWrapper = new EntityWrapper();
            fileWrapper.eq("child_user_id", auditVO.getId());
            fileWrapper.eq("business_type", 9);
            FileInfoDTO fileInfoDTO = fileInfoService.selectOne(fileWrapper);
            if(null != fileInfoDTO){
                auditVO.setIsExcel(1);
            }else{
                auditVO.setIsExcel(0);
            }
        }
        page.setRecords(auditVOList);
        return page;
    }

    @Override
    public Result<AuditVO> get(Long id) {
        AuditDTO dto = this.selectById(id);
        if(dto == null){
            return new Result();
        }
        AuditVO vo = new AuditVO();
        BeanUtils.copyProperties(dto, vo);
        List<AuditLogVO> logVOList = auditLogService.queryList(vo.getId());
        vo.setLogVOList(logVOList);
        return new Result(vo);
    }

    /**
     * 导入询价单
     * @param bo
     * @param input
     * @return
     */
    @Override
    public Result saveImportPurchase(AuditImportPurchaseSaveBO bo, byte[] input, FileInfoSaveBO saveBo) {
        AuditSaveBO auditSaveBO = new AuditSaveBO ();
        PurchaseInfoImportSaveBO purchaseInfoImportSaveBO = new PurchaseInfoImportSaveBO ();

        purchaseInfoImportSaveBO.setCreateUserId (bo.getCreateUserId ()); //创建用户id
        purchaseInfoImportSaveBO.setCreateUserName (bo.getCreateUserName ()); //创建用户名称
        purchaseInfoImportSaveBO.setShopId (bo.getShopId ()); //店铺id
        purchaseInfoImportSaveBO.setShopName (bo.getShopName ()); //公司名称
        purchaseInfoImportSaveBO.setName (bo.getName ()); //名称
        purchaseInfoImportSaveBO.setPublishType (bo.getPublishType ()); //发布类型 0买家发布、1admin发布，2admin代客发布
        purchaseInfoImportSaveBO.setExpiredTime (bo.getExpiredTime ()); // 过期时间
        purchaseInfoImportSaveBO.setAcceptEditStatus (bo.getAcceptEditStatus ()); //是否同意平台修改 0不同意、1同意(必填)
        Result result = purchaseInfoService.analyzePurchaseExcel (purchaseInfoImportSaveBO, input);
        if (result.getCode () == 0 && result.getData () != null){
            PurchaseInfoSaveBO purchaseInfoSaveBO = (PurchaseInfoSaveBO)result.getData ();
            String params = JSON.toJSONString (purchaseInfoSaveBO, SerializerFeature.WriteNullStringAsEmpty);
            auditSaveBO.setParams (params); // 审核内容
            auditSaveBO.setShopId (bo.getShopId ()); //店铺id
            auditSaveBO.setId (bo.getId ());
            auditSaveBO.setStatus (0); //审核状态 0审核中，1审核通过，2审核打回，3审核不通过,4重新提交
            auditSaveBO.setType (bo.getType ()); //审核类型 0注册，1开店，2资质变更，3新增品牌，4新增类目,5店铺变更、6采购
            auditSaveBO.setContent (bo.getContent ()); // 审核意见
            Result save = save (auditSaveBO,saveBo);
            return save;
        }
        return result;
    }


    private List<CommodityCategoryTreeVO> getCTree(ArrayList<Long> ids){
        List<CommodityCategoryTreeVO> root = new ArrayList<>();
        for ( Long id : ids) {
            List<CommodityCategoryTreeVO> byChildId = this.getByChildId(id, ShoppingCodeEnum.AUDIT_CREATE.getCode(), new ArrayList<>());
            root.addAll(byChildId);
        }
        //查询最顶级的类目
        Wrapper<CommodityCategoryDTO> wrapperParent = new EntityWrapper<>();
        wrapperParent.eq("is_publish", 1).eq("status", 0)
                .eq("parent_id", 0).orderBy("sort", true);
        List<CommodityCategoryDTO> parentList = iCommodityCategoryService.selectList(wrapperParent);
        for (CommodityCategoryDTO commodityCategoryDTO : parentList) {
            CommodityCategoryTreeVO commodityCategoryTreeVO = new CommodityCategoryTreeVO();
            BeanUtils.copyProperties(commodityCategoryDTO, commodityCategoryTreeVO);
            root.add(commodityCategoryTreeVO);
        }
        //去重
        List<CommodityCategoryTreeVO> realRoot = root.stream().distinct().collect(Collectors.toList());
        //构建树形结构
        List<CommodityCategoryTreeVO> list = this.builTree(realRoot);
        List<CommodityCategoryTreeVO> real = new ArrayList<>();
        for (CommodityCategoryTreeVO categoryTreeVO : list) {
            real.addAll(categoryTreeVO.getChildList());
        }

        return real.stream().distinct().collect(Collectors.toList());
    }

    /**
     * description: 建立树形结构
     * param: [menuList]
     * author: chenyu.wang
     * date: 2020-07-28
     * return: java.util.List<com.ztgf.commodity.models.vo.CommodityCategoryTreeVO>
     */
    public List<CommodityCategoryTreeVO> builTree(List<CommodityCategoryTreeVO> menuList) {
        List<CommodityCategoryTreeVO> treeMenus = new ArrayList<>();
        for (CommodityCategoryTreeVO menuNode : getRootNode(menuList)) {
            menuNode = this.buildChilTree(menuNode, menuList);
            treeMenus.add(menuNode);
        }
        return treeMenus;
    }

    /**
     * description: 递归，建立子树形结构
     * param: [pNode, menuList]
     * author: chenyu.wang
     * date: 2020-07-28
     * return: com.ztgf.commodity.models.vo.CommodityCategoryTreeVO
     */
    private CommodityCategoryTreeVO buildChilTree(CommodityCategoryTreeVO pNode, List<CommodityCategoryTreeVO> menuList) {
        List<CommodityCategoryTreeVO> chilMenus = new ArrayList<>();
        for (CommodityCategoryTreeVO menuNode : menuList) {
            if (menuNode.getParentId().equals(pNode.getId())) {
                chilMenus.add(this.buildChilTree(menuNode, menuList));
            }
        }
        pNode.setChildList(chilMenus);
        return pNode;
    }

    /**
     * description: 获取根节点
     * param: [menuList]
     * author: chenyu.wang
     * date: 2020-07-28
     * return: java.util.List<com.ztgf.commodity.models.vo.CommodityCategoryTreeVO>
     */
    private List<CommodityCategoryTreeVO> getRootNode(List<CommodityCategoryTreeVO> menuList) {
        List<CommodityCategoryTreeVO> rootMenuLists = new ArrayList<>();
        for (CommodityCategoryTreeVO menuNode : menuList) {
            if (menuNode.getParentId().intValue() == 0) {
                rootMenuLists.add(menuNode);
            }
        }
        return rootMenuLists;
    }

    /**
     * description: 根据最终极类目id查询所有上级list
     * param: [id, list]
     * author: chenyu.wang
     * date: 2020-07-28
     * return: java.util.List<com.ztgf.commodity.models.vo.CommodityCategoryTreeVO>
     */
    public List<CommodityCategoryTreeVO> getByChildId(Long id, Integer status, List<CommodityCategoryTreeVO> list) {
        if (list == null) {
            list = new ArrayList<>();
        }
        CommodityCategoryDTO dto = iCommodityCategoryService.selectById(id);
        if (dto == null) {
            return null;
        }
        if (dto.getParentId() == 0) {
            return list;
        } else {
            CommodityCategoryTreeVO treeVO = new CommodityCategoryTreeVO();
            treeVO.setId(dto.getId());
            treeVO.setName(dto.getName());
            treeVO.setInitials(dto.getInitials());
            treeVO.setParentId(dto.getParentId());
            treeVO.setSort(dto.getSort());
            treeVO.setCode(dto.getCode());
            treeVO.setStatus(status);
            list.add(treeVO);
        }
        return this.getByChildId(dto.getParentId(), status, list);
    }
}
